const util = require('../../utils/util')
let p

Page({

	data: {
		cardStatus: 0,
		cardBalance: false,
		cardTranBalance: false,
		cardExpend: false,
		tradeList: [],
		loadingPanel: {
			tip: '同步中'
		}
	},

	temp: {
		cardId: ''
	},

	onLoad: function (options) {
		p = this
		util.userLogin({
			p,
			scene: 'other',
			complete: () => {
				util.showNotices(p)
				p.getCardData({
					success: (data) => {
						p.setCardData(data)
					},
					fail: (code, msg) => {
						util.hideLoadingPanel(p)
						util.error('同步失败', util.errorHandler(code, msg))
					}
				})
			},
			fail: (title, msg) => {
				wx.navigateBack({
					delta: 1
				})
				util.error(title, msg)
			},
			notBind: () => {
				util.modal('绑定提示', '只有登录和绑定身份后才能使用此功能哦，即将跳转到主页', () => {
					wx.switchTab({
						url: '/pages/home/home'
					})
				})
			}
		})
	},

	onUnload: () => {
		util.unloadPage('card')
	},

	getCardData: (obj) => {
		const {sync, success, fail} = obj
		util.request({
			source: 'card',
			method: sync ? 'put' : 'get',
			uri: `user/${util.getUserType()}/card`,
			data: {
				session: util.globalData('session')
			},
			success: (data) => {
				console.log(data)
				success(data)
			},
			fail
		})
	},

	setCardData: (data) => {
		const { cardId, cardNum, cardStatus, cardBalance, cardTranBalance, cardExpend, tradeList } = data
		p.temp.cardId = cardId
		tradeList.sort((a, b) => {
			return b.tradeTime - a.tradeTime
		})
		wx.setNavigationBarTitle({
			title: `一卡通（${cardNum}）`
		})
		if (cardStatus == 1) {
			util.modal('冻结提示', '此一卡通已被学校系统冻结，原因可能是某笔刷卡记录未进入一卡通中心导致未扣余额，在刷卡时又把此笔交易进行扣款，余额不足扣款时卡余额变成负数而被冻结，请到充卡处阿叔那解冻哦')
			wx.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: '#666666'
			})
		}
		p.setData({
			cardStatus,
			cardBalance,
			cardTranBalance,
			cardExpend,
			tradeList
		})
		util.hideLoadingPanel(p)
	},

	onPullDownRefresh: function () {
		wx.showModal({
			title: '是否同步？',
			content: '此操作将同步最新的一卡通记录（半小时后进入本页面也会自动同步最新数据），消费记录一般在消费后半小时内同步完成',
			success: (res) => {
				if(res.confirm) {
					wx.stopPullDownRefresh()
					util.showLoadingPanel(p, '同步中')
					p.getCardData({
						sync: true,
						success: (data) => {
							p.setCardData(data)
							util.tip({ p, text: '同步成功' })
						},
						fail: (code, msg) => {
							util.hideLoadingPanel(p)
							util.error('同步失败', util.errorHandler(code, msg))
						}
					})
				}
				else
					wx.stopPullDownRefresh()
			}
		})
	},

	onShareAppMessage: function () {
		return {
			title: '有了创新盒子，再也不怕找不到饭卡消费记录了',
			path: '/pages/card/card'
		}
	}

})